﻿using LibraryManagementSystem;
using System;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace LibraryManagementSystem
{
    public partial class LoginForm : Form
    {
        public LoginForm()
        {
            InitializeComponent();
            DatabaseConfig.InitializeDatabase();
            txtPassword.PasswordChar = '*';
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            string username = txtUsername.Text.Trim();
            string password = txtPassword.Text;

            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
            {
                MessageBox.Show("请输入用户名和密码", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            User user = AuthenticateUser(username, password);

            if (user != null)
            {
                this.Hide();

                if (user.IsAdmin)
                {
                    FormAdmin FormAdmin = new FormAdmin(user);
                    FormAdmin.Show();
                }
                else
                {
                    FormUser FormUser = new FormUser(user);
                    FormUser.Show();
                }
            }
            else
            {
                MessageBox.Show("用户名或密码错误", "登录失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private User AuthenticateUser(string username, string password)
        {
            using (var connection = DatabaseConfig.GetConnection())
            {
                connection.Open();

                string query = "SELECT * FROM Users WHERE Username = @username";
                var command = new SqlCommand(query, connection);
                command.Parameters.AddWithValue("@username", username);

                using (var reader = command.ExecuteReader())
                {
                    if (reader.Read())
                    {
                        string storedHash = reader["PasswordHash"].ToString();
                        string salt = reader["Salt"].ToString();
                        string inputHash = SecurityHelper.HashPasswordWithSalt(password, salt);

                        if (storedHash == inputHash)
                        {
                            return new User
                            {
                                Id = Convert.ToInt32(reader["Id"]),
                                Username = reader["Username"].ToString(),
                                Name = reader["Name"].ToString(),
                                //考虑是否需要电话和邮件
                                //Email = reader["Email"].ToString(),
                                //Phone = reader["Phone"].ToString(),
                                IsAdmin = Convert.ToBoolean(reader["IsAdmin"]),
                                CreatedAt = Convert.ToDateTime(reader["CreatedAt"])
                            };
                        }
                    }
                }
                return null;
            }
        }

        private void chkShowPassword_CheckedChanged(object sender, EventArgs e)
        {
            txtPassword.PasswordChar = chkShowPassword.Checked ? '\0' : '*';
        }

        private void lnkRegister_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            RegisterForm registerForm = new RegisterForm();
            registerForm.ShowDialog();
        }
    }
}